<script lang="ts" setup>
import type { SelectProps } from 'ant-design-vue';
import type { SelectValue } from 'ant-design-vue/es/select';
import { ref } from 'vue';
import { getFloors, getRoomsByFloor, saveRoom } from '@/service/api/room';

defineOptions({
  name: 'SeatArea'
});

const floorValue = ref();
const roomValue = ref();

const roomId = ref<number>();

const floorOptions = ref<SelectProps['options']>([]);
const roomOptions = ref<SelectProps['options']>([]);

const rows = ref();
const cols = ref();

// 存储表格数据，-1为默认的空白状态
const tableData = ref<number[][]>([]);

// 生成表格数据，确保保留现有数据
const changeRoom = () => {
  saveRoom({ roomId: roomId.value, row: rows.value, column: cols.value });

  const newTableData: number[][] = [];

  // 确保表格的行数和列数匹配
  for (let rowIndex = 0; rowIndex < rows.value; rowIndex += 1) {
    const newRow: number[] = [];
    for (let colIndex = 0; colIndex < cols.value; colIndex += 1) {
      // 如果新的行列数大于旧的数据，就填充为-1（空白）
      if (tableData.value[rowIndex] && tableData.value[rowIndex][colIndex] !== undefined) {
        newRow.push(tableData.value[rowIndex][colIndex]); // 保留原有的数据
      } else {
        newRow.push(-1); // 新增的单元格填充为-1
      }
    }
    newTableData.push(newRow);
  }

  tableData.value = newTableData;
};

getFloors().then(res => {
  if (res.data.length === 0) {
    return;
  }

  floorValue.value = res.data[0];
  res.data = Array.from(res.data);
  res.data.forEach((element: number) => {
    floorOptions.value?.push({ label: element, value: element });
  });

  getRoomsByFloor(floorValue.value).then(rooms => {
    roomId.value = rooms.data[0].roomId;
    roomValue.value = rooms.data[0].roomName;
    rows.value = rooms.data[0].row;
    cols.value = rooms.data[0].column;
    tableData.value = rooms.data[0].seatInfo;
    rooms.data = Array.from(rooms.data);
    rooms.data.forEach((element: any) => {
      roomOptions.value?.push({ label: element.roomName, value: element.roomName });
    });
  });
});

// 切换座位状态
const toggleSeat = (rowIndex: number, colIndex: number) => {
  const currentStatus = tableData.value[rowIndex][colIndex];
  if (currentStatus === -1) {
    tableData.value[rowIndex][colIndex] = 0; // 从空白变为空位（0）
  } else if (currentStatus === 0) {
    tableData.value[rowIndex][colIndex] = 1; // 从空位（0）变为已预约（1）
  } else if (currentStatus === 1) {
    tableData.value[rowIndex][colIndex] = 2; // 从已预约（1）变为书桌（2）
  } else if (currentStatus === 2) {
    tableData.value[rowIndex][colIndex] = -1; // 从书桌（2）变为空白（-1）
  }
  saveRoom({ roomId: roomId.value, row: rows.value, column: cols.value, seatInfo: tableData.value });
};

// 获取图标
const getIcon = (status: number) => {
  if (status === -1) return ''; // 空白没有图标
  if (status === 0) return '🪑'; // 空位
  if (status === 1) return '🔒'; // 已预约
  return ''; // 默认无图标
};

// 获取单元格背景颜色
const getCellStyle = (status: number) => {
  if (status === 2) {
    return { backgroundColor: 'tan' }; // 棕色背景用于书桌状态（2）
  }
  return {}; // 其他状态不改变背景颜色
};

const focusFloor = () => {};

const handleChangeFloor = (value: SelectValue) => {
  roomOptions.value = [];
  getRoomsByFloor(value as number).then(rooms => {
    roomId.value = rooms.data[0].roomId;
    roomValue.value = rooms.data[0].roomName;
    rows.value = rooms.data[0].row;
    cols.value = rooms.data[0].column;
    tableData.value = rooms.data[0].seatInfo;
    rooms.data = Array.from(rooms.data);
    rooms.data.forEach((element: any) => {
      roomOptions.value?.push({ label: element.roomName, value: element.roomName });
    });
  });
};

const focusRoom = () => {};

const handleChangeRoom = () => {
  getRoomsByFloor(floorValue.value).then(rooms => {
    rooms.data = Array.from(rooms.data);
    rooms.data.forEach((elment: any) => {
      if (elment.roomName === roomValue.value) {
        roomId.value = elment.roomId;
        rows.value = elment.row;
        cols.value = elment.column;
        tableData.value = elment.seatInfo;
      }
    });
  });
};
</script>

<template>
  <ACard
    :bordered="false"
    :body-style="{ flex: 1, overflow: 'hidden' }"
    class="flex-col-stretch sm:flex-1-hidden card-wrapper"
  >
    <div class="table-container">
      <!-- 控制面板 -->
      <div class="controls">
        <label>楼层：</label>
        <ASelect
          ref="select"
          v-model:value="floorValue"
          style="width: 64px; margin-right: 40px"
          size="small"
          :options="floorOptions"
          @focus="focusFloor"
          @change="handleChangeFloor"
        ></ASelect>
        <label>阅览室：</label>
        <ASelect
          ref="select"
          v-model:value="roomValue"
          size="small"
          style="width: 144px; margin-right: 40px"
          :options="roomOptions"
          @focus="focusRoom"
          @change="handleChangeRoom"
        ></ASelect>

        <label for="rows">行数：</label>
        <AInputNumber
          id="rows"
          v-model:value="rows"
          min="1"
          max="500"
          style="width: 60px; margin-right: 40px"
          size="small"
          @change="changeRoom"
        />
        <label for="cols">列数：</label>
        <AInputNumber
          id="cols"
          v-model:value="cols"
          min="1"
          max="500"
          style="width: 60px"
          size="small"
          @change="changeRoom"
        />
      </div>

      <!-- 表格 -->
      <div class="scrollable-table">
        <table class="table">
          <tbody>
            <tr v-for="(row, rowIndex) in tableData" :key="'row-' + rowIndex">
              <td
                v-for="(cell, colIndex) in row"
                :key="'col-' + colIndex"
                class="cell"
                :class="[{ occupied: cell !== 0 && cell !== -1 }]"
                :style="getCellStyle(cell)"
                @click="toggleSeat(rowIndex, colIndex)"
              >
                <span v-if="cell !== 2">{{ getIcon(cell) }}</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </ACard>
</template>

<style scoped>
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
}

.table-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  height: 100%;
}

.controls {
  margin: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollable-table {
  width: 100%;
  height: calc(100vh - 80px); /* 全屏高度，减去控制面板的高度 */
  overflow: auto; /* 允许滚动 */
  margin-top: 20px;
}

.table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
}

td {
  width: 40px;
  height: 40px;
  text-align: center;
  border: 1px solid #ccc;
  cursor: pointer;
  font-size: 18px;
}

.cell {
  font-size: 20px;
}

.cell.occupied {
  background-color: #f0f0f0;
}

td:hover {
  background-color: #e0e0e0;
}

label {
  font-weight: bold;
}
</style>
